from rest_framework import serializers
from django_redis import get_redis_connection
from goods.models import SKU
from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex


class CategoriesListSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'


class SKUSearchSerializer(HaystackSerializer):
    object = CategoriesListSerializer()

    class Meta:
        index_classes = [SKUIndex]
        fields = ['text', 'object']


class SKUHistorSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('该商品不存在')
        return attrs

    def create(self, validated_data):
        user = self.context['request'].user
        conn = get_redis_connection('history')

        conn.lrem('history_%s' % user.username, 0, self.validated_data['sku_id'])

        conn.lpush('history_%s' % user.username, self.validated_data['sku_id'])

        conn.ltrim('history_%s' % user.username, 0, 4)

        return validated_data
